using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ExpertPdf.HtmlToPdf;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// Convert the HTML code from the specified URL to a PDF document and send the 
    /// document as an attachment to the browser
    /// </summary>
    private void ConvertURLToPDF()
    {
        string urlToConvert = textBoxWebPageURL.Text.Trim();

        // Create the PDF converter. Optionally you can specify the virtual browser 
        // width as parameter. 1024 pixels is default, 0 means autodetect
        PdfConverter pdfConverter = new PdfConverter();

        // set the license key - required
        //pdfConverter.LicenseKey = "put your license key here";

        // set the converter options - optional
        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
        pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;


        // set if header and footer are shown in the PDF - optional - default is false 
        pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked;
        pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked;
        // set to generate a pdf with selectable text or a pdf with embedded image - optional - default is true
        pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = radioConvertToSelectablePDF.Checked;
        // set if the HTML content is resized if necessary to fit the PDF page width - optional - default is true
        pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;
        // 
        // set the embedded fonts option - optional - default is false
        pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
        // set the live HTTP links option - optional - default is true
        pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked;

        if (radioConvertToSelectablePDF.Checked)
        {
            // set if the JavaScript is enabled during conversion to a PDF with selectable text 
            // - optional - default is false
            pdfConverter.ScriptsEnabled = cbClientScripts.Checked;
            // set if the ActiveX controls (like Flash player) are enabled during conversion 
            // to a PDF with selectable text - optional - default is false
            pdfConverter.ActiveXEnabled = cbActiveXEnabled.Checked;
        }
        else
        {
            // set if the JavaScript is enabled during conversion to a PDF with embedded image 
            // - optional - default is true
            pdfConverter.ScriptsEnabledInImage = cbClientScripts.Checked;
            // set if the ActiveX controls (like Flash player) are enabled during conversion 
            // to a PDF with embedded image - optional - default is true
            pdfConverter.ActiveXEnabledInImage = cbActiveXEnabled.Checked;
        }

        // set if the images in PDF are compressed with JPEG to reduce the PDF document size - optional - default is true
        pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;

        // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
        if (cbBookmarks.Checked)
        {
            pdfConverter.PdfBookmarkOptions.TagNames = new string[] { "H1", "H2" };
        }

        // set PDF security options - optional
        //pdfConverter.PdfSecurityOptions.CanPrint = true;
        //pdfConverter.PdfSecurityOptions.CanEditContent = true;
        //pdfConverter.PdfSecurityOptions.UserPassword = "";

        //set PDF document description - optional
        pdfConverter.PdfDocumentInfo.AuthorName = "ExpertPDF HTML to PDF Converter";

        // add HTML header
        if (cbAddHeader.Checked)
            AddHeader(pdfConverter);
        // add HTML footer
        if (cbAddFooter.Checked)
            AddFooter(pdfConverter);

        // Performs the conversion and get the pdf document bytes that you can further 
        // save to a file or send as a browser response
        byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert);

        // send the PDF document as a response to the browser for download
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=ConversionResult.pdf; size=" + pdfBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(pdfBytes);
        response.Flush();
        response.End();
    }


    /// <summary>
    /// Convert the HTML code from the specified URL to a JPEG image and send the 
    /// image as an attachment to the browser
    /// </summary>
    private void ConvertURLToImage()
    {
        string urlToConvert = textBoxWebPageURL.Text.Trim();

        // Create the Image converter. Optionally you can specify the virtual browser 
        // width as parameter. 1024 pixels is default, 0 means autodetect
        ImgConverter imgConverter = new ImgConverter();
        // set the license key
        //imgConverter.LicenseKey = "put your license key here";

        // set if the JavaScript is enabled during conversion - optional - default is true
        imgConverter.ScriptsEnabled = cbClientScripts.Checked;
        // set if the ActiveX controls (like Flash player) are enabled during conversion - optional - default is true
        imgConverter.ActiveXEnabled = cbActiveXEnabled.Checked;

        // Performs the conversion and get the image bytes that you can further 
        // save to a file or send as a browser response
        byte[] imgBytes = imgConverter.GetImageFromUrlBytes(urlToConvert, System.Drawing.Imaging.ImageFormat.Jpeg);

        // send the image as a response to the browser for download
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=ConversionResult.jpeg; size=" + imgBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(imgBytes);
        response.Flush();
        response.End();
    }


    /// <summary>
    /// Convert the specified HTML string to a PDF document and send the 
    /// document as an attachment to the browser
    /// </summary>
    private void ConvertHTMLStringToPDF()
    {
        string htmlString = textBoxHTMLCode.Text;
        string baseURL = textBoxBaseURL.Text.Trim();
        bool selectablePDF = radioConvertToSelectablePDF.Checked;

        // Create the PDF converter. Optionally you can specify the virtual browser 
        // width as parameter. 1024 pixels is default, 0 means autodetect
        PdfConverter pdfConverter = new PdfConverter();
        // set the license key
        //pdfConverter.LicenseKey = "put your license key here";
        // set the converter options
        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
        pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;

        // set if header and footer are shown in the PDF - optional - default is false 
        pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked;
        pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked;
        // set to generate a pdf with selectable text or a pdf with embedded image - optional - default is true
        pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = radioConvertToSelectablePDF.Checked;
        // set if the HTML content is resized if necessary to fit the PDF page width - optional - default is true
        pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;
        // 
        // set the embedded fonts option - optional - default is false
        pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
        // set the live HTTP links option - optional - default is true
        pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked;

        if (radioConvertToSelectablePDF.Checked)
        {
            // set if the JavaScript is enabled during conversion to a PDF with selectable text 
            // - optional - default is false
            pdfConverter.ScriptsEnabled = cbClientScripts.Checked;
            // set if the ActiveX controls (like Flash player) are enabled during conversion 
            // to a PDF with selectable text - optional - default is false
            pdfConverter.ActiveXEnabled = cbActiveXEnabled.Checked;
        }
        else
        {
            // set if the JavaScript is enabled during conversion to a PDF with embedded image 
            // - optional - default is true
            pdfConverter.ScriptsEnabledInImage = cbClientScripts.Checked;
            // set if the ActiveX controls (like Flash player) are enabled during conversion 
            // to a PDF with embedded image - optional - default is true
            pdfConverter.ActiveXEnabledInImage = cbActiveXEnabled.Checked;
        }

        // set if the images in PDF are compressed with JPEG to reduce the PDF document size - optional - default is true
        pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;

        // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
        if (cbBookmarks.Checked)
        {
            pdfConverter.PdfBookmarkOptions.TagNames = new string[] { "H1", "H2" };
        }

        // set PDF security options - optional
        //pdfConverter.PdfSecurityOptions.CanPrint = true;
        //pdfConverter.PdfSecurityOptions.CanEditContent = true;
        //pdfConverter.PdfSecurityOptions.UserPassword = "";

        //set PDF document description - optional
        pdfConverter.PdfDocumentInfo.AuthorName = "ExperPDF HTML to PDF Converter";

        // add HTML header
        if (cbAddHeader.Checked)
            AddHeader(pdfConverter);
        // add HTML footer
        if (cbAddFooter.Checked)
            AddFooter(pdfConverter);

        // Performs the conversion and get the pdf document bytes that you can further 
        // save to a file or send as a browser response
        //
        // The baseURL parameter helps the converter to get the CSS files and images
        // referenced by a relative URL in the HTML string. This option has efect only if the HTML string
        // contains a valid HEAD tag. The converter will automatically inserts a <BASE HREF="baseURL"> tag. 
        byte[] pdfBytes = null;
        if (baseURL.Length > 0)
            pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString, baseURL);
        else
            pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlString);

        // send the PDF document as a response to the browser for download
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=ConversionResult.pdf; size=" + pdfBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(pdfBytes);
        response.Flush();
        response.End();
    }


    /// <summary>
    /// Convert the specified HTML string to a JPEG image and send the 
    /// image as an attachment to the browser
    /// </summary>
    private void ConvertHTMLStringToImage()
    {
        string htmlString = textBoxHTMLCode.Text;
        string baseURL = textBoxBaseURL.Text.Trim();

        // Create the Image converter. Optionally you can specify the virtual browser 
        // width as parameter. 1024 pixels is default, 0 means autodetect
        ImgConverter imgConverter = new ImgConverter();
        // set the license key
        //imgConverter.LicenseKey = "put your license key here";

        // set if the JavaScript is enabled during conversion - optional - default is true
        imgConverter.ScriptsEnabled = cbClientScripts.Checked;
        // set if the ActiveX controls (like Flash player) are enabled during conversion - optional - default is true
        imgConverter.ActiveXEnabled = cbActiveXEnabled.Checked;

        // Performs the conversion and get the image bytes that you can further 
        // save to a file or send as a browser response
        //
        // The baseURL parameter helps the converter to get the CSS files and images
        // referenced by a relative URL in the HTML string. This option has efect only if the HTML string
        // contains a valid HEAD tag. The converter will automatically inserts a <BASE HREF="baseURL"> tag. 
        byte[] imgBytes = null;
        if (baseURL.Length > 0)
            imgBytes = imgConverter.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Jpeg, baseURL);
        else
            imgBytes = imgConverter.GetImageBytesFromHtmlString(htmlString, System.Drawing.Imaging.ImageFormat.Jpeg);

        // send the image as a response to the browser for download
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "binary/octet-stream");
        response.AddHeader("Content-Disposition",
            "attachment; filename=ConversionResult.jpeg; size=" + imgBytes.Length.ToString());
        response.Flush();
        response.BinaryWrite(imgBytes);
        response.Flush();
        response.End();
    }

    private void AddHeader(PdfConverter pdfConverter)
    {
        string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
        string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";

        //enable header
        pdfConverter.PdfDocumentOptions.ShowHeader = true;
        // set the header height in points
        pdfConverter.PdfHeaderOptions.HeaderHeight = 60;
        // set the header HTML area
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(0, 0, -1, pdfConverter.PdfHeaderOptions.HeaderHeight,
                    headerAndFooterHtmlUrl, 1024, -1);
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea.FitHeight = true;
        pdfConverter.PdfHeaderOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked;
    }

    private void AddFooter(PdfConverter pdfConverter)
    {
        string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
        string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";

        //enable footer
        pdfConverter.PdfDocumentOptions.ShowFooter = true;
        // set the footer height in points
        pdfConverter.PdfFooterOptions.FooterHeight = 60;
        //write the page number
        pdfConverter.PdfFooterOptions.TextArea = new TextArea(0, 30, "This is page &p; of &P;  ",
            new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
        pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true;
        pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right;
        // set the footer HTML area
        pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(0, 0, -1, pdfConverter.PdfFooterOptions.FooterHeight,
                    headerAndFooterHtmlUrl, 1024, -1);
        pdfConverter.PdfFooterOptions.HtmlToPdfArea.FitHeight = true;
        pdfConverter.PdfFooterOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked;
    }

    protected void btnConvert_Click(object sender, EventArgs e)
    {
        if (radioConvertURL.Checked)
        {
            // convert the HTML from a specified URL
            if (radioConvertToImage.Checked)
                ConvertURLToImage(); // convert URL to image
            else
                ConvertURLToPDF(); // convert URL to PDF
        }
        else
        {
            // convert the specified HTML string
            if (radioConvertToImage.Checked)
                ConvertHTMLStringToImage(); // convert HTML string to image
            else
                ConvertHTMLStringToPDF(); // convert HTML string to PDF
        }
    }
    protected void radioConvertURL_CheckedChanged(object sender, EventArgs e)
    {
        pnlConvertURL.Visible = radioConvertURL.Checked;
        pnlConvertHTML.Visible = !radioConvertURL.Checked;
    }
    protected void radioConvertHTML_CheckedChanged(object sender, EventArgs e)
    {
        pnlConvertURL.Visible = !radioConvertHTML.Checked;
        pnlConvertHTML.Visible = radioConvertHTML.Checked;
    }
}
